﻿using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.ServiceModel;
using System.Threading.Tasks;
using ServiceInterface.InputModels;
using ServiceInterface.ResponseModels;

namespace Web.Infrastructure.Interface
{
    public static class AIInterface
    {
        public static async Task<NewGameResponseModel> CreateGame(NewGameInputModel inputModel)
        {
            var request = await GetHttpClient().PostAsJsonAsync("api/CreateGame", inputModel);
            var response = await request.Content.ReadAsAsync<NewGameResponseModel>();

            return response;
        }

        public static async Task<NextMoveResponseModel> FindMove(FindNextMoveInputModel inputModel)
        {
            var request = await GetHttpClient().PostAsJsonAsync("api/FindMove", inputModel);
            var response = await request.Content.ReadAsAsync<NextMoveResponseModel>();

            return response;
        }

        private static HttpClient GetHttpClient()
        {
            HttpClient client;

            try
            {
                client = new HttpClient
                {
                    BaseAddress = new Uri("http://localhost:56089/")
                };
            }
            catch (Exception e)
            {
                throw new CommunicationException("Error while communicating with remote host. See inner exception for details.", e);
            }

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            return client;
        }
    }
}
